<template>
  <div class="movie-upload">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>上传电影数据</h2>
          <el-button @click="goToList">返回列表</el-button>
        </div>
      </template>

      <el-form
          ref="uploadForm"
          :model="formData"
          :rules="rules"
          label-width="120px"
      >
        <!-- 文件上传 -->
        <el-form-item label="Excel文件" prop="file">
          <el-upload
              class="excel-upload"
              :auto-upload="false"
              :show-file-list="true"
              :limit="1"
              accept=".xlsx,.xls"
              :on-change="handleFileChange"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传Excel文件，要求：
                <ul>
                  <li>支持 .xlsx 和 .xls 格式</li>
                  <li>第一列表头必须为 "name"（电影名称）</li>
                  <li>第二列表头必须为 "slug"（电影标识），需为英文。</li>
                  <li>第三列表头可选为 "content"（电影内容）</li>
                  <li>如果没有提供content，将使用模板中的内容</li>
                </ul>
                <el-button
                    link
                    type="primary"
                    @click="downloadTemplate"
                >
                  下载Excel模板
                </el-button>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 内容位置选择 -->
        <el-form-item label="内容位置" prop="contentPosition">
          <el-radio-group v-model="formData.contentPosition">
            <el-radio label="START">开头</el-radio>
            <el-radio label="END">结尾</el-radio>
            <el-radio label="MIDDLE">中间</el-radio>
            <el-radio label="RANDOM">随机</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 上传按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              :loading="loading"
              @click="submitUpload"
          >
            上传文件
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 结果对话框 -->
      <el-dialog
          v-model="resultDialogVisible"
          title="上传结果"
          width="50%"
      >
        <el-result
            :icon="uploadResult.success ? 'success' : 'error'"
            :title="uploadResult.success ? '上传成功' : '上传失败'"
            :sub-title="uploadResult.message"
        >
          <template #extra>
            <el-button @click="handleCloseDialog">确定</el-button>
          </template>
        </el-result>
      </el-dialog>

      <!-- 进度展示 -->
      <el-dialog
          v-model="progressVisible"
          title="处理进度"
          :close-on-click-modal="false"
          :show-close="false"
          width="500px"
      >
        <div class="progress-info">
          <el-progress
              :percentage="progressPercentage"
              :status="progressStatus"
          />
          <div class="progress-text">
            已处理: {{ progress.successCount + progress.failCount }} / {{ progress.totalCount }}
          </div>
          <div class="progress-stats">
            <span class="success">成功: {{ progress.successCount }}</span>
            <span class="fail">失败: {{ progress.failCount }}</span>
          </div>
        </div>
        <template #footer>
          <el-button
              @click="handleProgressComplete"
              v-if="isProcessComplete"
          >
            完成
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMoviesStore } from '@/stores/adminMovie'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()

  // 示例数据
  const exampleData = [
    ['name', 'slug', 'content'],  // 表头
    ['Biến Số Tình Yêu', 'The variable of love', '这是第一部电影的内容简介'],  // 示例数据1
    ['沉默的真相', 'The Silent Truth', '这是第二部电影的内容简介'],     // 示例数据2
    ['流浪地球', 'Wandering Earth', '']  // 示例数据3 - 没有content
  ]

  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(exampleData)

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '示例')

  // 生成Excel文件并下载
  XLSX.writeFile(wb, '电影导入模板.xlsx')
}

const progressVisible = ref(false)
const progressTimer = ref(null)
const progress = reactive({
  totalCount: 0,
  successCount: 0,
  failCount: 0,
  status: ''
})

const progressPercentage = computed(() => {
  if (!progress.totalCount) return 0
  return Math.round(
      ((progress.successCount + progress.failCount) / progress.totalCount) * 100
  )
})

const isProcessComplete = computed(() => {
  return ['COMPLETED', 'FAILED'].includes(progress.status)
})

// 添加进度条状态计算
const progressStatus = computed(() => {
  switch(progress.status) {
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
      return 'exception'
    default:
      return ''  // 处理中状态
  }
})

const startProgressCheck = (batchNo) => {
  progressVisible.value = true
  checkProgress(batchNo)
  progressTimer.value = setInterval(() => {
    checkProgress(batchNo)
  }, 2000)  // 每2秒检查一次进度
}

const checkProgress = async (batchNo) => {
  try {
    const response = await store.getBatchProgress(batchNo)
    Object.assign(progress, response.data)

    if (isProcessComplete.value) {
      clearInterval(progressTimer.value)
    }
  } catch (error) {
    ElMessage.error('获取进度失败')
    clearInterval(progressTimer.value)
  }
}

const handleProgressComplete = () => {
  progressVisible.value = false
  if (progress.status === 'COMPLETED') {
    router.push('/admin-json/list')
  }
}

const router = useRouter()
const store = useMoviesStore()
const uploadForm = ref(null)
const resultDialogVisible = ref(false)
const loading = ref(false)

const uploadResult = reactive({
  success: false,
  message: ''
})

const formData = reactive({
  name: '',
  contentPosition: 'START'
})

const rules = {
  name: [
    { required: true, message: '请输入电影名称', trigger: 'blur' }
  ],
  contentPosition: [
    { required: true, message: '请选择内容位置', trigger: 'change' }
  ]
}

// 文件选择处理
const handleFileChange = (file) => {
  formData.file = file.raw
}

const handleRemove = () => {
  formData.file = null
}

// 超出文件数量限制处理
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 提交上传
const submitUpload = async () => {
  if (!formData.file) {
    ElMessage.warning('请选择文件')
    return
  }

  loading.value = true
  try {
    const formPayload = new FormData()
    formPayload.append('file', formData.file)
    formPayload.append('contentPosition', formData.contentPosition)

    const response = await store.uploadMovieExcel(formPayload)
    console.log(response.data.batchNo)
    if (response.data.batchNo) {  // 如果返回了批次号，说明是异步处理

      startProgressCheck(response.data.batchNo)  // 开始检查进度
    } else {  // 否则显示普通结果
      uploadResult.success = true
      uploadResult.message = `成功处理 ${response.data.totalCount} 条数据`
      resultDialogVisible.value = true
    }
  } catch (error) {
    uploadResult.success = false
    uploadResult.message = error.message || '上传失败'
    resultDialogVisible.value = true
  } finally {
    loading.value = false
  }
}

// 处理对话框关闭
const handleCloseDialog = () => {
  store.resetUploadStatus()
  if (store.uploadStatus.success) {
    router.push('/admin-json/list')
  }
  resultDialogVisible.value = false
}

const goToList = () => {
  router.push('/admin-json/list')
}

onUnmounted(() => {
  if (progressTimer.value) {
    clearInterval(progressTimer.value)
  }
})
</script>

<style scoped>
.movie-upload {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.excel-upload {
  width: 100%;
  max-width: 360px;
}

.el-upload__tip {
  margin-top: 8px;
  color: #909399;
}
.progress-info {
  padding: 20px;
}

.progress-text {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.progress-stats {
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
}

.progress-stats .success {
  color: #67C23A;
  margin-right: 20px;
}

.progress-stats .fail {
  color: #F56C6C;
}
</style>